﻿using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using RotaractProjectCalendar.DataAccessLayer;
using RotaractProjectCalendar.ViewModels;

namespace RotaractProjectCalendar.Areas.Anonymous.Controllers
{
    [AllowAnonymous]
    public class ClubAccountController : Controller
    {
        public ClubAccountController()
            : this(new UserManager<ClubAccount>(new UserStore<ClubAccount>(new CalendarContext())))
        {
        }

        private ClubAccountController(UserManager<ClubAccount> userManager)
        {
            UserManager = userManager;
        }

        private UserManager<ClubAccount> UserManager { get; set; }

        //
        // GET: /Anonymous/ClubAccount/Login
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Anonymous/ClubAccount/Login
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var user = await UserManager.FindAsync(model.UserName, model.Password);
            if(user != null)
            {
                await SignInAsync(user, model.RememberMe);
                return RedirectToLocal(returnUrl);
            }

            ModelState.AddModelError("", "Invalid username or password.");

            return View(model);
        }

        private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }

        private async Task SignInAsync(ClubAccount user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, identity);
        }

        private ActionResult RedirectToLocal(string returnUrl)
        {
            if(Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }

            return RedirectToAction("Index", "Project", User.IsInRole("Admin") ? 
                                                        new { area= "Admin"} 
                                                      : new { area = "User" });
        }
	}
}